import {
    BASE_URL
} from '../../../http/config';
Page({
            data: {
                userInfo: {},
                title: '',
                content: ''
            },

            onLoad() {
                const user = wx.getStorageSync('userInfo'); // 从缓存中获取用户信息

                if (user && user.id) {
                    this.setData({
                        userInfo: user
                    });
                } else {
                    const pages = getCurrentPages(); // 获取当前页面栈
                    const currentPage = pages[pages.length - 1];
                    // 获取当前客服页面的路径
                    const currentUrl = '/' + currentPage.route;

                    // 重定向到登录页面，附带当前客服页面路径以便登录后跳转回来
                    wx.redirectTo({
                        // 将原来的主页路径改为当前客服页面路径
                        url: `/pages/login/login?url=${encodeURIComponent(currentUrl)}`
                    });
                }
            },

    onShow() {
       
    },

    onTitleInput(e) {
        this.setData({
            title: e.detail.value
        });
    },

    onContentInput(e) {
        this.setData({
            content: e.detail.value
        });
    },

    onCancel() {
        wx.navigateBack();
    },

    onConfirm() {
        const {
            title,
            content,
            userInfo
        } = this.data;

        if (!title.trim()) {
            wx.showToast({
                title: '标题不能为空',
                icon: 'none'
            });
            return;
        }

        if (!userInfo || !userInfo.id) {
            wx.showToast({
                title: '用户未登录',
                icon: 'none'
            });
            return;
        }

        wx.request({
            url: `${BASE_URL}/question/add`,
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                title: title,
                content: content,
                userId: userInfo.id
            },
            success(res) {
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '提交成功',
                        icon: 'success'
                    });
                    wx.navigateBack(); // 返回上一页
                } else {
                    wx.showToast({
                        title: '提交失败',
                        icon: 'none'
                    });
                }
            },
            fail(err) {
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
                console.error(err);
            }
        });
    }
});
